import React, { FC, useContext } from "react";
import classNames from 'classnames';
import { SelectContext } from './select'
import Icon from '../icon'

export interface optionsProps {
    value: string // 默认根据此属性值进行筛选，该值不能相同
    index?: string
    label?: string  //选项的标签，若不设置则默认与 value 相同
    disabled?: boolean //是否禁用该选项
}

const Option: FC<optionsProps> = (props) => {
    // props
    const { value, index, label, disabled, children } = props
    // state
    // other 上下文 
    const context = useContext(SelectContext)
    const { onSelect, selectedValues, multiple } = context
    const isSelected = selectedValues.includes(value);
    // ----
    const classes = classNames('viking-select-item', {
        'is-disabled': disabled,
        'is-selected': isSelected,
    })
    // methods 
    const handleClick = (e: React.MouseEvent, value: string, isSelected: boolean) => {
        e.preventDefault();
        if (onSelect && !disabled) {
            onSelect(value, isSelected);
        }
    }
    return (
        <li key={index} className={classes} onClick={(e) => handleClick(e, value, isSelected)}>
            { children || (label ? label : value)}
            { multiple && isSelected && <Icon icon='check' />}
        </li>
    )
}

Option.displayName = 'Option'
export default Option